<template>
    <div class="views-changdiyuyue-list">
        <div>
            <el-card class="box-card">
                <template #header>
                    <div class="clearfix"  style="width: 500px">
                      <span class="title"> 场地预约查询 （只能提前3个小时取消预约）</span>
                    </div>
                </template>

                <div class="form-search">
                    <el-form @submit.prevent.stop :inline="true" size="small">
                        <el-form-item label="场地编号">
                            <el-input v-model="search.changdibianhao"></el-input>
                        </el-form-item>
                        <el-form-item label="场地名称">
                            <el-input v-model="search.changdimingcheng"></el-input>
                        </el-form-item>
                        <el-form-item label="类型">
                            <el-select v-model="search.leixing"
                                ><el-option label="请选择" value=""></el-option
                                ><e-select-option type="option" module="changdileixing" value="id" label="leixingmingcheng"></e-select-option
                            ></el-select>
                        </el-form-item>
                        <el-form-item label="预约编号">
                            <el-input v-model="search.yuyuebianhao"></el-input>
                        </el-form-item>
                        <el-form-item label="预约时段">
                            <el-select v-model="search.yuyueshiduan"
                                ><el-option label="请选择" value=""></el-option><el-option label="08：00-10：00" value="08：00-10：00"></el-option>
                                <el-option label="10：00-12：00" value="10：00-12：00"></el-option>
                                <el-option label="12：00-14：00" value="12：00-14：00"></el-option>
                                <el-option label="14：00-16：00" value="14：00-16：00"></el-option>
                                <el-option label="16：00-18：00" value="16：00-18：00"></el-option>
                                <el-option label="18：00-20：00" value="18：00-20：00"></el-option>
                                <el-option label="20：00-22：00" value="20：00-22：00"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="预约状态">
                            <el-select v-model="search.yuyuezhuangtai"
                                ><el-option label="请选择" value=""></el-option><el-option label="待支付" value="待支付"></el-option>
                                <el-option label="已预约" value="已预约"></el-option>
                                <el-option label="已取消" value="已取消"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="searchSubmit" icon="el-icon-search">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <el-table border :data="lists" style="width: 100%" @sort-change="sortChange" highlight-current-row>
                    <el-table-column type="index" label="#"></el-table-column>
                    <!-- 序号 -->

                    <el-table-column prop="changdibianhao" label="场地编号" width="130">
                        <template #default="{row}"> {{ row.changdibianhao }} </template>
                    </el-table-column>
                    <el-table-column prop="changdimingcheng" label="场地名称" width="130">
                        <template #default="{row}"> {{ row.changdimingcheng }} </template>
                    </el-table-column>
                    <el-table-column sortable="custom" prop="changdijiage" label="场地价格" width="110">
                        <template #default="{row}"> {{row.changdijiage}} </template>
                    </el-table-column>
                    <el-table-column prop="leixing" label="类型" width="80">
                        <template #default="{row}"> <e-select-view module="changdileixing" :value="row.leixing" select="id" show="leixingmingcheng"></e-select-view> </template>
                    </el-table-column>
                    <el-table-column prop="yuyuebianhao" label="预约编号" width="130">
                        <template #default="{row}"> {{ row.yuyuebianhao }} </template>
                    </el-table-column>
                    <el-table-column prop="yuyueshijian" label="预约时间" width="120">
                        <template #default="{row}"> {{ row.yuyueshijian }} </template>
                    </el-table-column>
                    <el-table-column prop="yuyueshiduan" label="预约时段" width="120">
                        <template #default="{row}"> {{ row.yuyueshiduan }} </template>
                    </el-table-column>

                  <el-table-column label="是否支付" width="120">
                    <template #default="{row}">
                      {{ row.iszf }}
                      <el-button
                          size="small"
                          type="primary"
                          @click="$goto({path:'/admin/pay' , query:{biao:'changdiyuyue' , id:row.id,ordersn:row.yuyuebianhao,zongji:row.changdijiage,isShaxiang:'' } })"
                          v-if="row.iszf=='否'"
                      >
                        去支付
                      </el-button>
                    </template>
                  </el-table-column>


                  <el-table-column prop="yuyuezhuangtai" label="预约状态" width="100">
                    <template #default="{row}"> {{ row.yuyuezhuangtai }} </template>
                  </el-table-column>

                    <el-table-column prop="beizhu" label="备注" width="100">
                        <template #default="{row}"> {{ row.beizhu }} </template>
                    </el-table-column>




                    <el-table-column prop="yuyueren" label="预约人" width="200">
                        <template #default="{row}">
                            <e-user-info module="yonghu" name="xingming" touxiang="touxiang" username="yonghuming" :value="row.yuyueren">
                                <template #default="{user}">
                                    <div class="user-info-desc">
                                        <span> {{ user.lianxifangshi }} </span>
                                    </div>
                                </template>
                            </e-user-info>
                        </template>
                    </el-table-column>



                  <el-table-column label="操作" fixed="right" width="250">
                    <template #default="{row}">
                      <el-button-group>

                        <el-button
                            type="primary"
                            v-if="row.yuyuezhuangtai === '已预约' && canCancel(row)"
                            :icon="Plus"
                            size="small"
                            @click="$router.push('/admin/quxiaoyuyue/add?id='+row.id)"
                        >
                          取消预约
                        </el-button>

                        <el-tooltip effect="dark" content="详情" placement="top-start"
                        ><el-button type="info" :icon="InfoFilled" size="small" @click="$router.push('/admin/changdiyuyue/detail?id='+row.id)">详情</el-button>
                        </el-tooltip>

                        <el-tooltip effect="dark" content="删除" placement="top-start" v-if="row.iszf == '否' || row.yuyuezhuangtai == '已取消'"
                        ><el-button type="danger" :icon="Delete" size="small" @click="deleteItems(row.id)">删除</el-button>
                        </el-tooltip>
                      </el-button-group>
                    </template>
                  </el-table-column>
                </el-table>
              <div class="e-pages" style="margin-top: 10px; text-align: center">
                <el-pagination
                    @current-change="loadList"
                    :page-sizes="[12, 24, 36, 48,60]"
                    v-model:current-page="search.page"
                    v-model:page-size="search.pagesize"
                    @size-change="sizeChange"
                    layout="total, sizes, prev, pager, next"
                    :total="totalCount"
                >
                </el-pagination>
              </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import http from "@/utils/ajax/http";
import DB from "@/utils/db";
import router from "@/router";

import { ref, reactive, watch, unref, onBeforeMount } from "vue";
import { useRoute } from "vue-router";
import { session } from "@/utils/utils";
import { canChangdiyuyueSelect, useChangdiyuyueSelect, canChangdiyuyueDelete } from "@/module";
import { extend } from "@/utils/extend";
import { ElMessageBox, ElMessage } from "element-plus";
import { Plus, Search, InfoFilled, Edit, Delete } from "@element-plus/icons-vue";

const route = useRoute();
const search = reactive({
  changdiid: "",
  changdibianhao: "",
  changdimingcheng: "",
  yuyuebianhao: "",
  yuyueshiduan: "",
  yuyuezhuangtai: "",
  page: 1, // 当前页
  pagesize: 12, // 每页行数
  orderby: "id", // 排序字段
  sort: "desc", // 排序类型
});
extend(search, route.query);
// 链接参数变化时更新这些内容
watch(
    () => route.query,
    () => {
      extend(search, route.query);
      loadList(1);
    },
    { deep: true }
);

// 总行数
const totalCount = ref(0);
/**
 * 列表数据
 * @type {EChangdiyuyue[]}
 */
const lists = ref([]);
// 加载状态
const loading = ref(false);


const canCancel = (row) => {
  try {
    const yuyueDate = row.yuyueshijian; // 预约日期
    const yuyueShiduan = row.yuyueshiduan; // 预约时段

    if (!yuyueDate || !yuyueShiduan) return false;

    // 提取时段开始时间并格式化
    const startTime = yuyueShiduan.split('-')[0].trim().replace(/：/g, ':');
    const appointmentTime = new Date(`${yuyueDate} ${startTime}`);

    if (isNaN(appointmentTime)) return false;

    // 计算截止时间（提前3小时）
    const deadline = new Date(appointmentTime.getTime() - 3 * 3600 * 1000);
    return new Date() < deadline;
  } catch {
    return false;
  }
};


// 排序操作
const sortChange = (e) => {
  console.log(e);
  if (e.order == null) {
    search.orderby = "id";
    search.sort = "desc";
  } else {
    search.orderby = e.prop;
    search.sort = e.order == "ascending" ? "asc" : "desc";
  }
  loadList(1);
};
// 设置页数多少
const sizeChange = (e) => {
  search.pagesize = e;
  loadList(1);
};

const deleteItems = (ids) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm("确定删除？")
        .then((res) => {
          canChangdiyuyueDelete(ids).then((res) => {
            if (res.code == 0) {
              ElMessage.success("删除成功");
              loadList(search.page);
              resolve(res.data);
            } else {
              ElMessage.error(res.msg);
            }
          });
        })
        .catch((err) => {
          reject(err);
        });
  });
};

// 加载场地预约列表方法
const loadList = (page) => {
  // 加载
  if (unref(loading)) return;
  loading.value = true;
  search.page = page;

  http.post("/api/changdiyuyue/selectYuyueren", search).then(
      (res) => {
        loading.value = false;
        if (res.code == 0) {
          var data = res.data;
          lists.value = data.lists.records;
          totalCount.value = data.lists.total;
        }
      },
      (err) => {
        loading.value = false;
        ElMessage.error(err.message);
      }
  );
};

onBeforeMount(() => {
  loadList(1);
});
const searchSubmit = () => {
  loadList(1);
};
</script>

<style scoped lang="scss">
.views-changdiyuyue-list {
}
</style>
